package xyz.thoughtset.viewer.common.connector.linker;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xyz.thoughtset.viewer.common.connector.entity.bo.ConnectorMeta;
import xyz.thoughtset.viewer.common.connector.entity.bo.Linker;

import java.security.Security;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class LinkerHelper{
    static {
        Security.addProvider(new BouncyCastleProvider());
    }
    @Getter
    private static final List<String> connectorKeys = new ArrayList<>();
    private static final Map<String, ConnBuilder> connectorCache = new ConcurrentHashMap<>();
    private static final Map<String, LinkerBuilder> linkerTypeCache = new ConcurrentHashMap<>();

    public static ConnBuilder getConnBuilder(ConnectorMeta connectorMeta) {
        String linkerType = connectorMeta.getLinkerType();
        ConnBuilder connBuilder = connectorCache.get(connectorMeta.getLinkerType());
//        if (Objects.nonNull(connBuilder)) {
//            return connBuilder;
//        }
//        LinkerBuilder linkerBuilder = linkerTypeCache.get(linkerType);
//        connBuilder = linkerBuilder.buildConnBuilder();
//        connectorCache.put(linkerType, connBuilder);
        return connBuilder;
    }

    public static ConnBuilder createConnBuilder(Linker linker) {
        LinkerBuilder linkerBuilder = linkerTypeCache.get(linker.getLinkerType());
        ConnBuilder connBuilder = linkerBuilder.buildConnBuilder(linker);
        registerConnectorToCache(linker.getId(), connBuilder);
        return connBuilder;
    }

    public static LinkerBuilder getLinkerBuilder(String linkId) {
        return linkerTypeCache.get(linkId);
    }

    public static String getTarExecType(String linkId) {
        if (!connectorCache.containsKey(linkId)) {
            log.error("Linker not found for id: {}", linkId);
            return null;
        }
        return connectorCache.get(linkId).dataLinker.getLinkerType();
    }

    public static void registerConn(ConnBuilder connBuilder) {
        Linker linker = connBuilder.getDataLinker();
        registerConnectorToCache(linker.getId(), connBuilder);
    }

    public static void registerLinkerBuilder(LinkerBuilder linkerBuilder,String supportType) {
        linkerTypeCache.put(supportType,linkerBuilder);
    }

    private static void registerConnectorToCache(String key,ConnBuilder connBuilder) {
        connectorKeys.add(key);
        connectorCache.put(key, connBuilder);
    }

}
